package dataDraw.stateDiagramDraw;

import data.DataVector;
import data.Position;
import data.stateDiagram.State;
import dataDraw.Constants;
import dataDraw.TextDraw;

import java.awt.*;

/**
 * User: Szymon Kudzia
 * Date: 11.05.13
 * Time: 13:39
 */
public class BasicStateDraw implements StateDraw {
	protected TextDraw textDraw;
	protected Graphics graphics;

	@Override
	public void draw(State state, Graphics graphics) {
		this.graphics = graphics;
		textDraw.setGraphics(graphics);

		updateSize(state);

		drawBackground(state);
		drawName(state);

		if (state == DataVector.getInstance().getActiveStateDiagram().getStateDiagram().getActiveState()) {
			drawEnvelope(state.getPosition());
		}
	}

	protected void drawName(State state) {
		textDraw.drawString(state.getName(), getTextPosition(state));
	}

	protected void drawBackground(State state) {
		graphics.drawRoundRect(state.getPosition().getX(), state.getPosition().getY(),
				state.getPosition().getWidth(), state.getPosition().getHeight(), 10, 10);
	}

	protected void updateSize(State state) {
		state.getPosition().setWidth(getTextSize(state.getName()).getWidth() + 4 * Constants.MARGIN);
		state.getPosition().setHeight(getTextSize(state.getName()).getHeight() + 4 * Constants.MARGIN);
	}

	protected Position getTextPosition(State state) {
		Position strSize = getTextSize(state.getName());
		Position stateSize = state.getPosition();

		return new Position(state.getPosition().getX() + stateSize.getWidth() / 2 - strSize.getWidth() / 2 - Constants.MARGIN,
				state.getPosition().getY() + Constants.MARGIN);
	}

	protected Position getTextSize(String str) {
		Position p = new Position(graphics.getFontMetrics().stringWidth(str),
				graphics.getFontMetrics().getHeight());

		p.setHeight(p.getY());
		p.setWidth(p.getX());

		return p;
	}

	private void drawEnvelope(Position current) {
		graphics.setColor(Color.red);

		graphics.drawRect(current.getFirstX() - Constants.MARGIN,
				current.getFirstY() - Constants.MARGIN,
				current.getWidth() + 2 * Constants.MARGIN,
				current.getHeight() + 2 * Constants.MARGIN);

		graphics.setColor(Color.black);
	}

	public void setTextDraw(TextDraw textDraw) {
		this.textDraw = textDraw;
	}
}
